<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
class TijiaoController extends Controller
{
    //
    public function Index(Request $request)
    {
    	// dd($request->all());
    	$goods = session('cart');
    	// $user = session('user');
    	// dd($goods);
    	$data = [];

    	foreach($goods as $k=>$v){
    		$tem = DB::table('goodsmain')->where('id',$v['id'])->first();
    		$tem->num = $v['num'];
    		$data[]=$tem;
    	}
    	// dd($data);
    	//传一个商品到订单pid里面
    	$pid= [];
    	foreach ($data as $kk => $vv) {
    		$pid[]=$vv->id;
    	}
    	$pids  =  implode ( "," ,  $pid );
    	$num = count(explode(",",$pids));
    	// dd($num);
    	for($j=1; $j<=$num; $j++){
    		$sn[]='0';
    	}
    	// dd($sn);
    	$status = implode("," , $sn);
    	// dd($status);
    	$jiage = [];
    	foreach($data as $k=>$v){
    		if(empty($v->price)){
    			$jiage[]=$v->hwprice * $v->num;
    		}else{
    			$jiage[]=$v->price * $v->num;
    		}
    		
    	}
    	// dd($jiage);
    	$zongjia = '';
    	foreach($jiage as $v){
    		$zongjia+=$v;
    	}
    	// dd($zongjia);
    	$user = session('user');
        // dd($user->userId);
        $address = DB::table('storeaddress')->where('uid',$user->userId)->first();
        // dd($address->uid);
        
        //随机出来订单号
    	$id = time()+rand(1,9999);
    	DB::table('dingdan')->insert(['id'=>$id,'uid'=>$address->uid,'price'=>$zongjia,'pid'=>$pids,'status'=>$status]);
    	return view('home.tijiaodingdan',['zongjia'=>$zongjia,'id'=>$id,'address'=>$address]);
	}
    	
    
}
